import { Toast } from 'usuuu'

/**
 * 用户状态共享
 */
export const useUser = (): Ref<UserVo | null> => {
    return useState('user', () => null)
}
/**
 * 更新用户信息
 */
export const useUserInfo = async (paramsId?: string) => {
    const user = useUser()
    const loginUserId = useLoginUserId()
    const validateAuth = useValidateAuth()
    const token = useCookie('token', {
        domain: '.usuuu.com',
        maxAge: 86400
    })
    if (token.value) {
        //获取Redis中用户信息
        const data = await redisUserApi()
        //写入用户信息
        user.value = data.data
        if (data.code !== 200) {
            user.value = null
            token.value = null
        }
    }
    //写入登陆用户ID
    loginUserId.value = user.value ? user.value.id : null
    //是否是自己的主页
    validateAuth.value = paramsId == user.value?.id
}
/**
 * 退出登录
 */
export const useSignOut = async () => {
    const user = useUser()
    const token = useCookie('token', {
        domain: '.usuuu.com',
        maxAge: 86400
    })
    //退出登陆
    const data = await loginOutApi()
    if (data.code == 200) {
        user.value = null
        token.value = null
        Toast.open(data.msg)
    } else {
        Toast.open(data.msg)
    }
}